package com.glsc.ngateway.platform.controller;

import com.glsc.ngateway.common.api.flowable.dto.*;
import com.glsc.ngateway.common.api.flowable.feign.IFeignFlowableService;
import com.glsc.ngateway.common.api.flowable.resp.ResponseSituationEventDto;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.platform.service.EventManageService;
import com.glsc.ngateway.platform.service.FlowCommonService;
import com.glsc.ngateway.platform.utils.RequestTool;
import com.glsc.ngateway.platform.utils.TokenUtil;
import com.glsc.ngateway.platform.utils.report.ReportFileConfigEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/eventManage")
@Api(value = "事件管理流程接口", tags = {"事件管理流程接口"})
public class FlowEventManageController {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    private static int default_page_number = 1;
    private static int default_page_size = 10;


    @Resource
    private IFeignFlowableService feignDemandService;

    @Resource
    private EventManageService eventManageService;

    @Resource
    private TokenUtil tokenUtil;

    @Resource
    private RequestTool requestTool;

    @Resource
    private FlowCommonService flowCommonService;

    @Value("${demand.downloadUrl}")
    String downloadUrl;

    /**
     * 流程发起
     *
     * @param eventTaskDto 流程创建表单数据
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/createFlow")
    public PlatformResponse<FlowDoTaskRespDto> createFlow(@RequestBody EventTaskDto eventTaskDto) {
        PlatformResponse<FlowDoTaskRespDto> ret = null;
        try {

            String operatorStart = requestTool.getAccountFromRequest();
            FlowDoTaskRespDto respDto = eventManageService.createFlow(eventTaskDto, operatorStart);
            ret = PlatformResponse.successData(respDto);
        } catch (Exception e) {
            logger.error("createFlow！", e);
            ret = PlatformResponse.failedMsg("操作失败", e.getMessage());
        }

        return ret;
    }


    /**
     * 保存节点数据，但是不提交任务
     */
    @PostMapping("/saveFormData")
    @ApiOperation(value = "保存节点数据", notes = "保存节点数据")
    public PlatformResponse<FlowDoTaskRespDto> saveFormData(@RequestBody EventTaskDto eventTaskDto) {
        logger.info("保存节点数据，{}", eventTaskDto);

        String operatorStart = requestTool.getAccountFromRequest();

        FlowDoTaskRespDto respDto = eventManageService.saveFormData(eventTaskDto, operatorStart);
        return PlatformResponse.successData(respDto);
    }


    /**
     * 审核通过
     */
    @PostMapping("/taskAuditPass")
    @ApiOperation(value = "审核通过", notes = "流程审核处理通过")
    public PlatformResponse<FlowDoTaskRespDto> taskAuditPass(@RequestBody EventTaskDto taskDto) {
        logger.info("审核任务，" + taskDto);

        String operatorStart = requestTool.getAccountFromRequest();
        FlowDoTaskRespDto respDto = eventManageService.taskAuditPass(taskDto, operatorStart);
        return PlatformResponse.successData(respDto);
    }

    /**
     * 审核驳回
     */
    @PostMapping("/taskAuditReject")
    @ApiOperation(value = "审核驳回，返回上一个节点", notes = "流程审核驳回处理")
    public PlatformResponse<FlowDoTaskRespDto> taskAuditReject(@RequestBody EventTaskDto taskDto) {
        logger.info("驳回，返回上一个节点，" + taskDto);

        String operatorStart = requestTool.getAccountFromRequest();
        FlowDoTaskRespDto respDto = eventManageService.taskAuditReject(taskDto, operatorStart);

        return PlatformResponse.successData(respDto);
    }

    /**
     * 根据流程实例ID或者任务ID检索流程
     *
     * @param taskDto processId 流程ID
     * @param taskDto taskId 任务ID
     */
    @PostMapping("/findByProcessIdOrTaskId")
    @ApiOperation(value = "根据流程实例ID或者任务ID检索流程", notes = "根据流程实例ID或者任务ID检索流程状态、备注等，如提供流程实例ID则认为只读方式获取数据")
    public PlatformResponse<EventTaskDto> findByProcessIdOrTaskId(@RequestBody EventTaskDto taskDto) {
        logger.info("查询流程内容，" + taskDto);
        EventTaskDto respDto = eventManageService.getWorkFlowFormByTaskId(taskDto);
        return PlatformResponse.successData(respDto);
    }


    @ApiOperation(value = "流程分页查询-调试", notes = "流程分页查询")
    @RequestMapping("/findProcessPage")
    public PlatformResponse<Page<ResponseSituationEventDto>> getProcessSituationPage(
            @ApiParam(value = "流程查询参数") @RequestBody(required = true) FlowParamSearchDto paramSearchDto) {
        logger.info("流程已办列表分页查询");
        paramSearchDto.setSystemCode(Strings.isNotBlank(paramSearchDto.getSystemCode()) ? paramSearchDto.getSystemCode() : null);
        String operatorStart = requestTool.getAccountFromRequest();
        Page<ResponseSituationEventDto> page = eventManageService.getProcessSituationPage(paramSearchDto.getPageNo(), paramSearchDto.getPageSize(), paramSearchDto, operatorStart);
        return PlatformResponse.successData(page);
    }

    @ApiOperation(value = "流程分页查询-调试", notes = "流程分页查询")
    @RequestMapping("/export")
    public byte[] export(@ApiParam(value = "流程查询参数") @RequestBody FlowParamSearchDto paramSearchDto
            , HttpServletResponse response) throws IOException {
        response.setHeader("Content-Disposition", "attachment;" + "filename=" + URLEncoder.encode(ReportFileConfigEnum.EVENT_FLOW.getFileName(), "UTF-8"));
        String operatorStart = requestTool.getAccountFromRequest();
        return eventManageService.export(paramSearchDto, operatorStart);
    }

    /**
     * 事件统计
     */
    @PostMapping("/eventStatistics")
    @ApiOperation(value = "事件统计", notes = "事件统计")
    public PlatformResponse<Map> eventStatistics(@RequestBody(required = false) EventStatisticParamDto param) {
        String operatorStart = requestTool.getAccountFromRequest();
        Map<String, List<EventStatisticDto>> respDto = eventManageService.eventStatistics(param, operatorStart);
        return PlatformResponse.successData(respDto);
    }

}
